﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using System.Web.Security;
using System.Web.UI;
using SBACN.WebSite.Cache;
using SBACN.WebSite.Code;
using SBACN.WebSite.Common;
using SBACN.WebSite.Models;

namespace SBACN.WebSite.Admin.Systems
{
	public partial class UserList : AdminBasePage
	{
		public string SearchKeyWords
		{
			get
			{
				return txt_UserKeyWords.Value.Trim();
			}
		}
		protected void Page_Load(object sender, EventArgs e)
		{
			if(!Page.IsPostBack)
			{
				Expression<Func<TB_Member, bool>> fm = (p => true);
				Expression<Func<TB_Member, string>> om = (p => p.Name);
				var list = DAL.DALHelper.Instance.GetList<TB_Member, string>(fm, om, true).Select(p => new { Name = p.Name, ID = p.ID }).ToList();
				this.ddl_Member.AppendDataBoundItems = true;
				this.ddl_Member.DataSource = list;
				this.ddl_Member.DataTextField = "Name";
				this.ddl_Member.DataValueField = "ID";
				this.ddl_Member.DataBind();

				var roleList = RoleCache.Instance.CacheList.Where(p => p.Status).Select(p => new { Name = p.Name, ID = p.ID }).Distinct();
				this.ddl_Role.AppendDataBoundItems = true;
				this.ddl_Role.DataSource = roleList;
				this.ddl_Role.DataTextField = "Name";
				this.ddl_Role.DataValueField = "ID";
				this.ddl_Role.DataBind();
				InitCtrl();
			}
		}

		private void InitCtrl()
		{
			string keywords = SearchKeyWords;
			Expression<Func<TB_Member, bool>> m = (p => p.Name.Contains(keywords) || p.EnName.Contains(keywords));
			IList<int> mlist = DAL.DALHelper.Instance.GetList<TB_Member>(m).Select(p => p.ID).ToList();
			Expression<Func<TB_User, bool>> f = (p => (keywords.Length == 0) || ((keywords.Length > 0) && (p.UserName.Contains(keywords) || p.NickName.Contains(keywords)) || mlist.Contains(p.MemberID)));
			Expression<Func<TB_User, int>> o = (p => p.MemberID);
			Expression<Func<TB_User, string>> r = (p => p.UserName);

			IList<TB_User> userList = DAL.DALHelper.Instance.GetList<TB_User, int, string>(f, o, true, r, true);
			this.rpt_User.DataSource = userList;
			this.rpt_User.DataBind();
		}

		public string GetRoleName(string userName)
		{
			TB_UserInRoles roleRelate = DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_UserInRoles>(p=>p.UserName == userName);
			if(roleRelate != null)
			{
				TB_Role role = RoleCache.Instance.CacheList.Where(p => p.ID == roleRelate.RoleID).FirstOrDefault();
				if(role != null)
				{
					return role.Name;
				}
			}
			return string.Empty;
		}

		public string GetMemberName(object mid)
		{
			int id = 0;
			if (mid != null && int.TryParse(mid.ToString(), out id))
			{
				if (id == -1)
				{
					return "后台系统用户";
				}
				TB_Member tm = DAL.DALHelper.Instance.GetObject<TB_Member>("ID", id);
				if (tm != null)
				{
					return tm.Name;
				}
			}
			return string.Empty;
		}

		protected void btn_Search_Click(object sender, EventArgs e)
		{
			InitCtrl();
		}

		protected void btn_Create_Click(object sender, EventArgs e)
		{
			string username = string.IsNullOrWhiteSpace(this.txt_Name.Text) ? this.hid_UserName.Value.Trim() : this.txt_Name.Text.Trim();
			string nickname = txt_NickName.Text.Trim();
			string email = txt_EMail.Text.Trim();
			string roleID = ddl_Role.SelectedValue;
			string memberID = ddl_Member.SelectedValue;
			int id = 0;
			int rid = 0;
			if(string.IsNullOrWhiteSpace(username))
			{
				this.lbl_Msg.Text = "用户名不能为空!";
				ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "$jqy(document).ready(function () {ShowBlock(false);});", true);
			}
			else if (string.IsNullOrWhiteSpace(email) || !(email.LastIndexOf(".") > (email.IndexOf("@") + 1) && email.IndexOf("@") > 1 && email.LastIndexOf(".") < email.Length - 2))
			{
				this.lbl_Msg.Text = "邮件地址不能为空或邮件地址不正确!";
				ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "$jqy(document).ready(function () {ShowBlock(false);});", true);
			}
			else if (string.IsNullOrWhiteSpace(roleID) || !int.TryParse(roleID, out rid))
			{
				this.lbl_Msg.Text = "必须选择权限角色!";
				ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "$jqy(document).ready(function () {ShowBlock(false);});", true);
			}
			else if (!int.TryParse(memberID, out id))
			{
				this.lbl_Msg.Text = "用户分类选择有误!";
				ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "$jqy(document).ready(function () {ShowBlock(false);});", true);
			}
			else
			{
				#region 表单验证通过，更改数据库数据
				if (!string.IsNullOrWhiteSpace(this.hid_UserName.Value))//edit
				{
					#region 修改用户信息
					string name = this.hid_UserName.Value.Trim();
					TB_User user = DAL.DALHelper.Instance.GetObject<TB_User>("UserName", name);
					if(user != null)
					{
						user.NickName = nickname;
						user.EMail = email;
						user.Status = rbl_Status.SelectedValue == "1";
						user.MemberID = id;

						TB_UserInRoles role = DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_UserInRoles>(p => p.UserName == user.UserName);
						if (role == null)
						{
							role = DAL.DALHelper.Instance.Create<TB_UserInRoles>();
							role.RoleID = rid;
							role.UserName = user.UserName;
							DAL.DALHelper.Instance.Add(role);
						}
						else if (role.RoleID != rid)
						{
							role.RoleID = rid;
							DAL.DALHelper.Instance.Update(role);
						}

						user.CreateBy = AdminBasePage.AdminInfo.UserName;
						user.CreateDate = DateTime.Now;
						DAL.DALHelper.Instance.SaveChanges();
						this.lbl_MainMsg.Text = "用户信息修改成功!";
					}
					#endregion
				}
				else//create
				{
					#region 创建新用户
					string password = GeneratePassword(8);
					TB_User user = DAL.DALHelper.Instance.GetObject<TB_User>("UserName", username);
					if (user != null)
					{
						this.lbl_Msg.Text = "该用户名已存在!";
						ClientScript.RegisterClientScriptBlock(this.GetType(), "Msg", "$jqy(document).ready(function () {ShowBlock(false);});", true);
					}
					else
					{
						user = DAL.DALHelper.Instance.Create<TB_User>();
						user.UserName = username;
						string passwordmd5 = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5").ToLower();
						user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(passwordmd5, "MD5").ToLower();
						user.NickName = nickname;
						user.EMail = email;
						user.Status = rbl_Status.SelectedValue == "1";
						user.MemberID = id;
						user.CreateBy = AdminBasePage.AdminInfo.UserName;
						user.CreateDate = DateTime.Now;
						DAL.DALHelper.Instance.Add(user);
						DAL.DALHelper.Instance.SaveChanges();

						TB_UserInRoles role = DAL.DALHelper.Instance.GetFirstOrDefaultObject<TB_UserInRoles>(p => p.UserName == user.UserName);
						if (role == null)
						{
							role = DAL.DALHelper.Instance.Create<TB_UserInRoles>();
							role.RoleID = rid;
							role.UserName = user.UserName;
							DAL.DALHelper.Instance.Add(role);
						}
						else if (role.RoleID != rid)
						{
							role.RoleID = rid;
							DAL.DALHelper.Instance.Update(role);
						}
						DAL.DALHelper.Instance.SaveChanges();

						TB_SystemConfig config = SystemConfigCache.Instance["00090007"].Where(p => p.Code == "5").FirstOrDefault();
						if (config != null && config.Status)
						{
							Mail.Instance.SendEMail(config.Name.Replace("$Name", user.UserName), config.Value.Replace("$Name", user.UserName).Replace("$Password", password), email);
						}
						this.lbl_MainMsg.Text = "用户创建成功!";
					}
					#endregion
				}
				#endregion
				UserRightCache.Instance.Clear();
				InitCtrl();
			}
		}

		protected void btn_Delete_Click(object sender, EventArgs e)
		{
			if(!string.IsNullOrWhiteSpace(this.hid_UserName.Value))
			{
				string name = hid_UserName.Value.Trim();
				TB_User user = DAL.DALHelper.Instance.GetObject<TB_User>("UserName", name);
				if(user != null)
				{
					user.Status = !user.Status;
					DAL.DALHelper.Instance.Update(user);
					DAL.DALHelper.Instance.SaveChanges();
					UserRightCache.Instance.Clear();
					this.lbl_MainMsg.Text = string.Empty;
					InitCtrl();
				}
			}
		}

		protected void btn_RestPwd_Click(object sender, EventArgs e)
		{
			string username = this.hid_UserName.Value.Trim();
			string password = GeneratePassword(8);
			if(!string.IsNullOrWhiteSpace(username))
			{
				TB_User user = DAL.DALHelper.Instance.GetObject<TB_User>("UserName", username);
				if(user != null)
				{
					string passwordmd5 = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5").ToLower();
					user.Password = FormsAuthentication.HashPasswordForStoringInConfigFile(passwordmd5, "MD5").ToLower();
					user.CreateBy = AdminBasePage.AdminInfo.UserName;
					user.CreateDate = DateTime.Now;
					DAL.DALHelper.Instance.Update(user);
					DAL.DALHelper.Instance.SaveChanges();

					TB_SystemConfig config = SystemConfigCache.Instance["00090007"].Where(p => p.Code == "6").FirstOrDefault();
					if (config != null && config.Status)
					{
						Mail.Instance.SendEMail(config.Name.Replace("$Name", user.UserName), config.Value.Replace("$Name", user.UserName).Replace("$Password", password), user.EMail);
					}
					this.lbl_MainMsg.Text = "新密码已经发送至用户邮箱!";
					UserRightCache.Instance.Clear();
					InitCtrl();
				}
			}
		}
	}
}